package org.wattdepot.cli;

import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.util.tstamp.Tstamp;
import javax.xml.datatype.XMLGregorianCalendar;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * Creates a chart of power generated or consumed through one plant in one
 * specified period of time during specified intervals, into a input file name.
 * @author wing
 *
 */
public class ChartCommand extends CommandLineInterface implements WattDepotCliCommand {

  /**
   * Gets all the data from WattDepot.
   * @param source power plant
   * @param startDay date
   * @param endDay date
   * @param interval how many checks for the days specified
   * @param file for the output image
   * @throws WattDepotClientException for anything that goes wrong
   */
  /**
   * This method prints out information to help users.
   * @param args list of strings input
   * @return a string of commands
   */
  @Override
  public String doCommand(List<String> args) {
    
    String type = args.get(0);
    String source = args.get(1);
    String startDay = args.get(2);
    String endDay = args.get(3);
    String interval = args.get(4);
    String file = args.get(5);
    String result = "Chart unsuccessful";
    String consumedOption = "consumed";
    String generatedOption = "generated";
    
    /**This method contains modified code taken from the writing wattdepot clients wiki
    http://code.google.com/p/wattdepot/wiki/WritingWattDepotClients#1.7_
    Charting_data_from_WattDepot
    **/
    Integer intervalInt = 1;
    
    try {
      intervalInt = Integer.parseInt(interval);
    }
    catch (NumberFormatException e) {
      return "Problem with the interval inputted";
    }
    //Integer intervalMinutes = intervalInt;
    //double[] timeStampList = new double[intervalInt];
    int maxUriLength = 2048;
    StringBuffer chartUri = new StringBuffer(maxUriLength);
    double power = 0.0;
    double minPower = Double.MAX_VALUE;
    double maxPower = Double.MIN_VALUE;
    XMLGregorianCalendar startTime = null;
    XMLGregorianCalendar endTime = null;
    XMLGregorianCalendar timeStampCurrent = null;
    try {
      startTime = Tstamp.makeTimestamp(startDay);
      endTime = Tstamp.makeTimestamp(endDay);
    }
    catch (Exception e) {
      System.out.println("should never happen.");
    }

    chartUri.append("http://chart.apis.google.com/chart?chs=250x100&cht=lc&chd=t:");
    timeStampCurrent = startTime;
    //generate power data
    while (Tstamp.lessThan(timeStampCurrent, endTime)) {
      try {
      //both cases require source and timestamp 
      if (type.equalsIgnoreCase(consumedOption)) {
        power = client.getPowerConsumed(source, timeStampCurrent) / 1000000;
      }
      
      else if (type.equalsIgnoreCase(generatedOption)) { 
        power = client.getPowerGenerated(source, timeStampCurrent) / 1000000;
      }
      
      }
      catch (NotAuthorizedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      catch (ResourceNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      catch (BadXmlException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      catch (MiscClientException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      chartUri.append(String.format("%.1f,", power));
      
      if (power < minPower) {
        minPower = power;
      }
      
      if (power > maxPower) {
        maxPower = power;
      }
      
      timeStampCurrent = Tstamp.incrementMinutes(timeStampCurrent, intervalInt);
    }
    //generate image
    chartUri.deleteCharAt(chartUri.length() - 1);
    chartUri.append(String.format("&chds=%.1f,%.1f&chxt=y&chxr=0,%.1f,%.1f", minPower, maxPower,
        minPower, maxPower));
    System.out.format("Google Charts URI:%n%s%n", chartUri);
    //write to a file
    try {
      FileWriter fileWrite = new FileWriter(file);
      BufferedWriter bufferWrite = new BufferedWriter(fileWrite);
      bufferWrite.write("<html>");
      bufferWrite.write("<head>");
      bufferWrite.write("<title>" + "Power generated " + source + '-' + 
          startDay + " " + endDay + " Chart </title>");
      bufferWrite.write("</head>");
      bufferWrite.write("<body>");
      bufferWrite.write("<img src=" + chartUri.toString() + "/>");
      bufferWrite.write("</body");
      bufferWrite.write("</html>");
      bufferWrite.close();
      result = "Chart build successful";
      return result;
    }
    catch (FileNotFoundException fileNotFoundError) {
      System.out.println("File not found. Exiting program..");
    }
    catch (IOException inOutError) {
      System.out.println("I/O error. Exiting program..");
    }
   
    return result;
  }
  
}
